<?php
// include '../common/common.php';
// $content="350";
// user_menu_respon();
$CI = get_instance();
$CI->load->database();
function respon_text($contentStr)
{
    global $fromUsername,$toUsername,$time,$CI,$user_account;
    $contentStr = trim($contentStr);
    $textTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[%s]]></MsgType>
					<Content><![CDATA[%s]]></Content>
					<FuncFlag>0</FuncFlag>
					</xml>";
    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, "text", $contentStr);
    //recordUserBehavior($contentStr);
    echo $resultStr;
//    $CI->db->insert("",array('user_account'=>$user_account,'from_user'=>$fromUsername,'text'=>$contentStr,'time'=>time(),'user_reply'=>1));
    exit();
}

function respon_pics($title,$description,$picurl,$url)
{
    global $fromUsername,$toUsername,$time,$CI,$user_account;
    $countitem = count($title);
    if(!is_array($title)){
        $Tpl = "<item><Title><![CDATA[".$title."]]></Title> <Description><![CDATA[".$description."]]></Description><PicUrl><![CDATA[".$picurl."]]></PicUrl><Url><![CDATA[".$url."]]></Url></item>";
    }else{
        for ($i=0;$i<$countitem;$i++)
        {
            $from = "<item><Title><![CDATA[".$title[$i]."]]></Title> <Description><![CDATA[".$description[$i]."]]></Description><PicUrl><![CDATA[".$picurl[$i]."]]></PicUrl><Url><![CDATA[".$url[$i]."]]></Url></item>";
            $Tpl .= $from;
        }
    }
    $newsTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[%s]]></MsgType>
					<ArticleCount>%s</ArticleCount>
					<Articles>".$Tpl."</Articles>
					<FuncFlag>0</FuncFlag>
					</xml>";
    $resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, "news", $countitem);
    //recordUserBehavior($resultStr);
    echo $resultStr;
    if(is_array($title)){
        $title=implode(' | ', $title);
    }

    exit();
}
function user_respon()
{
    global $fromUsername,$toUsername,$content,$time,$CI,$user_account;
    $where['from_user'] = (string)$fromUsername;
    $step_info = $mongodb->weixin_user_step->findone($where);
    $menu_result = $mongodb->weixin_user_menu->findone(array('user_account'=>$user_account));
    if($content!='主菜单'){
        //var_dump(isset($step_info['step'])&&$step_info['time']<(time()-60*60*2));
        if(isset($step_info['step'])&&$step_info['time']<(time()-60*60*2)){//2个小时
            if($step_info['step']==='main'){
                $menu_num = 'main';
                $menu_now = check_in_keyword($menu_result,$menu_num);
                if($menu_now){
                    reply_by_type($menu_now);
                    break;
                }
            }else{
                $step_arr = explode('-',$step_info['step']);
                switch (count($step_arr)) {
                    case '1':
                        $menu_info = $menu_result['child_menu'][$step_arr[0]];
                        $menu_num = $step_arr[0];
                        break;
                    case '2':
                        $menu_info = $menu_result['child_menu'][$step_arr[0]]['child_menu'][$step_arr[1]];
                        $menu_num = $step_arr[0].'-'.$step_arr[1];
                        break;
                    case '3':
                        $menu_info = $menu_result['child_menu'][$step_arr[0]]['child_menu'][$step_arr[1]]['child_menu'][$step_arr[2]];
                        $menu_num = $step_arr[0].'-'.$step_arr[1].'-'.$step_arr[2];
                        break;
                    case '4':
                        $menu_info = $menu_result['child_menu'][$step_arr[0]]['child_menu'][$step_arr[1]]['child_menu'][$step_arr[2]]['child_menu'][$step_arr[3]];
                        $menu_num = $step_arr[0].'-'.$step_arr[1].'-'.$step_arr[2].'-'.$step_arr[3];
                        break;
                    case '5':
                        $menu_info = $menu_result['child_menu'][$step_arr[0]]['child_menu'][$step_arr[1]]['child_menu'][$step_arr[2]]['child_menu'][$step_arr[3]]['child_menu'][$step_arr[4]];
                        $menu_num = $step_arr[0].'-'.$step_arr[1].'-'.$step_arr[2].'-'.$step_arr[3].'-'.$step_arr[4];
                        break;
                }
                $menu_now = check_in_keyword($menu_info,$menu_num,$menu_result);
                //echo $menu_now.'222';
                if($menu_now){
                    reply_by_type($menu_now);
                    break;
                }
            }
        }else{
            $menu_num="main";
            $menu_now = check_in_keyword($menu_result,$menu_num);
            if($menu_now){
                reply_by_type($menu_now);
            }
        }
    }else{
        $mongodb->weixin_user_step->update($where,array('$set'=>array('step'=>'main','time'=>time())),array('upsert'=>true));
        reply_by_type($menu_result);
    }

}
function check_in_keyword($menu_info,$menu_num,$menu_result){
    global $fromUsername,$mongodb,$content;
    $flag=0;
    $where['from_user'] = (string)$fromUsername;
    if($content==='0'){
        if($menu_num!='main'){
            if(strrpos($menu_num,'-')){
                $menu_num = substr($menu_num,0,strrpos($menu_num,'-'));
                $step_arr = explode('-',$menu_num);
                switch (count($step_arr)) {
                    case '1':
                        $menu_new_info = $menu_result['child_menu'][$step_arr[0]];
                        break;
                    case '2':
                        $menu_new_info = $menu_result['child_menu'][$step_arr[0]]['child_menu'][$step_arr[1]];
                        break;
                    case '3':
                        $menu_new_info = $menu_result['child_menu'][$step_arr[0]]['child_menu'][$step_arr[1]]['child_menu'][$step_arr[2]];
                        break;
                    case '4':
                        $menu_new_info = $menu_result['child_menu'][$step_arr[0]]['child_menu'][$step_arr[1]]['child_menu'][$step_arr[2]]['child_menu'][$step_arr[3]];
                        break;
                }
                $mongodb->weixin_user_step->update($where,array('$set'=>array('step'=>$menu_num,'time'=>time())),array('upsert'=>true));
                return $menu_new_info;
            }else{
                $menu_num ='main';
                $mongodb->weixin_user_step->update($where,array('$set'=>array('step'=>$menu_num,'time'=>time())),array('upsert'=>true));
                return $menu_result;
            }
        }
        return $menu_info;
    }
    $value=is_array_has_keyword($menu_info,$content,$menu_num);
    if($value!=null)
    {
        return $value;
    }
    //var_dump(arr_foreach($menu_info));
    if($flag==0){
        $result=match_marketmaterial();
    }
    return $menu_info;
}

function is_array_has_keyword($array,$keywords,$menu_num)
{
    global $fromUsername,$mongodb,$content;
    $where['from_user'] = (string)$fromUsername;
    foreach ($array['child_menu'] as $key => $value) {
        if(is_array($value['keywords'])){
            foreach ($value['keywords'] as $value2) {
                if(strstr($content,$value2)){
                    $flag=1;
                    if($menu_num=='main'){
                        $menu_num = $key;
                    }else{
                        $menu_num .= '-'.$key;
                    }
                    //var_dump($menu_num);
                    $mongodb->weixin_user_step->update($where,array('$set'=>array('step'=>$menu_num,'time'=>time())),array('upsert'=>true));
                    return $value;
                }
            }
        }else{
            if(strstr($content,$value['keywords'])){
                $flag=1;
                if($menu_num=='main'){
                    $menu_num = $key;
                }else{
                    $menu_num .= '-'.$key;
                }
                //var_dump($menu_num);
                $mongodb->weixin_user_step->update($where,array('$set'=>array('step'=>$menu_num,'time'=>time())),array('upsert'=>true));
                return $value;
            }
        }
    }
    foreach($array as $key => $value)
    {
        if(is_array($value) )
        {
            $xxx=is_array_has_keyword($value,$keywords,$menu_num);
            if($xxx!=null)
            {
                return $xxx;
            }
        }

    }
}



function match_marketmaterial(){
    global $mongodb,$content,$fromUsername,$user_account,$base_url;
    $res_marketmaterial=$mongodb->material_marketing->find(array('email'=>$user_account))->sort(array('create_date'=>1));
    $flag=0;
    $i=0;
    foreach($res_marketmaterial as $item1){
        //var_dump($item1['label']);
        $arr_label=explode(',',str_replace('，',',',$item1['label']));
        foreach($arr_label as $item2){
            //echo $item2;
            if(strtolower($content)==strtolower($item2)&&$i<5){
                $flag=1;
                $str_title=str_replace('%', '%%', $item1['title']);
                $str_intro= htmlspecialchars(str_replace('%', '%%', $item1['intro']));
                if(strlen($str_title)>30){
                    $str_title=mb_substr($str_title, 0,50);
                }
                //respon_pics($str_title,$str_intro,$item1['image'],$base_url."index/talk/info2.php?id=".$item1['_id']);
                $img_title[]=$str_title;
                $img_description[]=$str_intro;
                $img_url[]=$item1['image'];
                $url[]=$base_url."index/talk/info2.php?id=".$item1['_id'];
                $i++;

                break;
            }
        }
    }
    if($flag==1){
        respon_pics($img_title,$img_description,$img_url,$url);
    }
    //echo $flag;
    return $flag;
}
function reply_by_type($menu_result){
    if($menu_result['type']=='text'){
        $contentStr = $menu_result['openning_text']."\r\n";
        foreach ($menu_result['child_menu'] as $key => $value) {
            //$contentStr .= ($key+1).'. '.$value['title']."\r\n";
        }
        $contentStr .= $menu_result['endding_text']."\r\n";
        respon_text($contentStr);
    }
    elseif($menu_result['type']=='single_pic'){
        respon_pics($menu_result['img_title'],$menu_result['description'],$menu_result['img_url'],$menu_result['url']);
    }
    elseif($menu_result['type']=='multi_pic'){
        foreach ($menu_result['imgs'] as $key => $value) {
            $img_description[] = $value['description'];
            $img_title[] = $value['img_title'];
            $img_url[] = $value['img_url'];
            $url[] = $value['url'];
        }
        respon_pics($img_title,$img_description,$img_url,$url);
    }

}
?>